package com.xgkj.diyiketang.fragment;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.LocationClient;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.activity.AllVideoListActivity;
import com.xgkj.diyiketang.activity.data.ListViewAdapter;
import com.xgkj.diyiketang.data.AdvertiseInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.FoodInfo;
import com.xgkj.diyiketang.data.VideoInfo;
import com.xgkj.diyiketang.data.VideoParentInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.AdvertisementTask;
import com.xgkj.diyiketang.task.FoodListTask;
import com.xgkj.diyiketang.task.GetUserDetailTask;
import com.xgkj.diyiketang.task.LiveListTask;
import com.xgkj.diyiketang.task.VideoListTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.LogUtils;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.PullToRefreshListView;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.yizhibo.Constants;

import java.util.ArrayList;
import java.util.List;

import static com.xgkj.diyiketang.activity.GuoxueVideoTwoActivity.used_minge;

/**
 * Created by XCKJ_Paladowow on 2016/5/23.
 */
public class Fragment_TuiJian extends BaseFragment implements PullToRefreshListView.OnRefreshListener {
    private Context mContext;
    private List<VideoInfo> mList = new ArrayList<VideoInfo>();
    private PullToRefreshListView mListView;
    private ListViewAdapter mListViewAdapter;
    private ArrayList<VideoParentInfo> mArrayList;
    private int getVideoListTaskId = -1;
    private int advertiseId = -1;
    private List<AdvertiseInfo> adList = new ArrayList<AdvertiseInfo>();
    private LocationManager mLocationManager;
    private String localstring;
    private int getfoodlistTaskId = -1;
    private int detailTaskId = -1;
    private EatShowUserInfo userInfo;
    private String areaid;
    private int currentPageAll = 1;
    public String schoolName = "";
    private int shouyeliveTaskId = -1;
    private int currentPage = 1;
    private int size = 4;
    private String flag;
    private String tag;
    private String pay_success = "";

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tuijian, null);
        mContext = getActivity();
        initView(view);
//        getUserDetail();
        isShow = true;
        return view;
    }

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    private void initView(View view) {
        if (!TextUtils.isEmpty(EatShowApp.getACache().getAsString("pay_success"))) {
            pay_success = EatShowApp.getACache().getAsString("pay_success");
        }
        if (getEatShowApp().getmUserInfo() != null) {
            schoolName = getEatShowApp().getmUserInfo().getSchoolName();
        }
        localstring = EatShowSetting.getInstance(mContext).getLocal();
        mListView = (PullToRefreshListView) view.findViewById(R.id.listView);
        mListView.init(mContext, true);
        mListViewAdapter = new ListViewAdapter(mContext);
        mListView.setAdapter(mListViewAdapter, true);
        mListView.setOnRefreshListener(this);
        // mListView.setOnLoadDataListener(this);
        mListView.doRefresh();
    }

    private void getLiveList() {
        LiveListTask task = new LiveListTask(size, currentPage, null, null, 2, "", "", "", "", "", "0", "1");
        task.addListener(new VideoListListner(mContext));
        shouyeliveTaskId = getEatShowApp().getTaskManager().addTask(task);
    }


    private void getAdList() {
//        if (advertiseId != -1) {
//            return;
//        }
        if (currentPageAll == 0) {
            mListView.setNoNextPage();
            return;
        }

        AdvertisementTask adtask = new AdvertisementTask("2", "7");
        adtask.addListener(new VideoListListner(mContext));
        advertiseId = getEatShowApp().getTaskManager().addTask(adtask);
    }

    public void getViewList() {
        VideoListTask task = new VideoListTask("", "1");
        task.addListener(new VideoListListner(mContext));
        getVideoListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }


    public void getfoodList() {
        localstring = EatShowSetting.getInstance(mContext).getLocal();
        PalLog.e("切换后的城市", localstring);
        FoodListTask ftask = new FoodListTask(10, 1, localstring);
        ftask.addListener(new VideoListListner(mContext));
        getfoodlistTaskId = getEatShowApp().getTaskManager().addTask(ftask);
    }

//    @Override
//    public void onPullRefresh() {
//
//    }
//
//    @Override
//    public void onLoadMore() {
//       // getAdList();
//    }

    @Override
    public void onRefresh() {
        currentPageAll = 1;
        getAdList();
    }

    class VideoListListner extends ShowToastTaskEventListener {

        public VideoListListner(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == getVideoListTaskId) {
                mListViewAdapter.clearData();
                mListView.onRefreshComplete();

                if (data != null) {
                    List<VideoParentInfo> pinfoList = (List<VideoParentInfo>) data;

//                    int counts =0;
//                    for (int i=0;i<pinfoList.size();i++){
//                        counts += pinfoList.get(i).getList().size();
//                    }
//                    PalLog.e("zongshu",counts+"");
//                    if(counts==0){
//                        schoolName="";
//                        ToastUtil.showMessage(mContext,"您所选择的学校暂未上传视频，已为您推荐了7777" +
//                                "热门视频");
//                        getViewList();
//                    }else {
//                        mListViewAdapter.updateData(pinfoList);
//                    }
                    if (pinfoList != null && pinfoList.size() > 0) {
                        mListViewAdapter.updateData(pinfoList);
                        TextView viewMore = new TextView(mContext);
                        viewMore.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewUtil.dip2px(mContext, 40)));
                        viewMore.setText("随便看看");
                        viewMore.setTextColor(getResources().getColor(R.color.gray));
                        viewMore.setTextSize(1, 15);
                        viewMore.setGravity(Gravity.CENTER);
                        viewMore.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent aIntent = new Intent(mContext, AllVideoListActivity.class);
                                startActivity(aIntent);
                            }
                        });
                        if (mListView.getFooterViewsCount() == 0) {
                            mListView.addFooterView(viewMore);
                        }
                    }


                }
            } else if (taskId == advertiseId) {
                advertiseId = -1;

                if (data != null) {
                    adList = (List<AdvertiseInfo>) data;
                    mListViewAdapter.addImageView(adList);
//                    getfoodList();
                    getLiveList();
                    getViewList();
                }


                // currentPageAll = result;
                PalLog.e("dangqiang", currentPageAll + "");
            } else if (taskId == getfoodlistTaskId) {
                if (data != null) {
                    List<FoodInfo> mfoodlist = new ArrayList<FoodInfo>();
                    int pageCount = 0;
                    int currentPage = 0;
                    int nextPage = 0;

                    JSONObject jsonString = (JSONObject) data;
                    currentPage = jsonString.getIntValue(ProtocolConst.CURRENT_PAGE);
                    pageCount = jsonString.getIntValue(ProtocolConst.PAGE_COUNT);
                    nextPage = currentPage >= pageCount ? 0 : (currentPage + 1);
                    areaid = jsonString.getString("areaId");
                    mListViewAdapter.setAreaId(areaid);
                    mfoodlist = JSON.parseArray(jsonString.getString(ProtocolConst.LIST_TAG), FoodInfo.class);
                    mListViewAdapter.addFoodList(mfoodlist);
                    getViewList();
                }

            } else if (taskId == shouyeliveTaskId) {
                List<EatShowUserInfo> fansList = new ArrayList<EatShowUserInfo>();
                if (data != null) {
                    fansList = (List<EatShowUserInfo>) data;
                }

                if (fansList != null && fansList.size() > 0) {
                    mListViewAdapter.addZhiboList(fansList);
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            mListView.onRefreshComplete();
            if (taskId == advertiseId) {
                advertiseId = -1;
//                getfoodList();
                getViewList();
            } else if (taskId == getfoodlistTaskId) {
                getViewList();
            } else if (taskId == getVideoListTaskId) {
//                schoolName = "";
//                getViewList();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isShow = true;
            if (mListViewAdapter != null && mListViewAdapter.getCount() == 0) {
                mListView.doRefresh();
            }
        } else {
            isShow = false;
        }
    }

    private boolean isShow;

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(pay_success)) {
            if (pay_success.equals("true")){
                pay_success="";
                getViewList();
                getLiveList();
                ToastUtil.showMessage(getActivity(), "观看券寄售成功");
            }

        }
        if (!TextUtils.isEmpty(EatShowApp.getACache().getAsString(Constants.USE_GUANKANQUAN))){
            String isUse = EatShowApp.getACache().getAsString(Constants.USE_GUANKANQUAN);
            if (isUse.equals("true")){
                getViewList();
                getLiveList();
            }
        }
        if (isShow) {
            if (mListViewAdapter != null && mListViewAdapter.getCount() == 0) {
                mListView.doRefresh();
            }
        }
    }
}
